package info.wegosoft.android.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import info.wegosoft.R;
import info.wegosoft.android.adapter.CommentAdapter;
import info.wegosoft.android.model.Comment;
import info.wegosoft.android.model.MBlog;
import info.wegosoft.android.model.Platform;
import info.wegosoft.android.qauth.sina.OAuthConstant;
import info.wegosoft.android.qauth.sina.Weibo;
import info.wegosoft.android.qauth.sina.WeiboException;
import info.wegosoft.android.qauth.tencent.OAuth;
import info.wegosoft.android.qauth.tencent.QWeiboSyncApi;
import info.wegosoft.android.qauth.tencent.QWeiboType.ResultType;
import info.wegosoft.android.util.TimeUtil;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/**  
 * Filename:    CommentListActivity.java 
 * Package:     info.wegosoft.android.activity 
 * Description: 评论列表Activity。由于新浪无法根据评论id拿到此id之前的列表，只能用整个列表刷新的方式载入更多
 * 				腾讯使用根据评论id拿到此id之前的列表的载入更多方法
 * Copyright:   Copyright (c) wegosoft.info 2011  
 * @author:     李辉 
 * email:       fzlihui@gmail.com
 * @version:    1.0  
 * Create at:   2011-6-23 下午05:16:36  
 */
public class CommentListActivity extends ListActivity {

	private CommentAdapter commentAdapter;
	private MBlog mblog;
	private int platformType;
	private ProgressDialog progressDialog;
	private List<Comment> commentList;
	private LinearLayout lastRowView;	
	private TextView lastStateText;
	private ProgressBar lastLoading;
	
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.comment_list);
		
		mblog = (MBlog) getIntent().getSerializableExtra("mblog");
		
		SharedPreferences preference = this.getSharedPreferences("platform",Context.MODE_PRIVATE);
    	
    	platformType = preference.getInt("type", -1);
		
    	//初始化界面
    	initUI();

		//初始化数据
    	initData();
	
	}
	
	/**
	 * 初始化界面
	 */
	private void initUI(){
		
		ImageButton commentBackBtn = (ImageButton) findViewById(R.id.commentBackBtn);
		
		commentBackBtn.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				
				Intent intent = new Intent();
				
				Bundle bundle = new Bundle();
				
				bundle.putSerializable("mblog", mblog);
				
				intent.putExtras(bundle);
				
				intent.setClass(CommentListActivity.this, DetailMBlogActivity.class);
				
				CommentListActivity.this.finish();
				
				startActivity(intent);
				
			}
		});
		
		Button commentBtn = (Button) findViewById(R.id.commentBtn);
		
		commentBtn.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				
				Intent intent = new Intent();
				
				Bundle bundle = new Bundle();
				
				bundle.putSerializable("mblog", mblog);
				
				intent.putExtras(bundle);
				
				intent.setClass(CommentListActivity.this, CommentMBlogActivity.class);
				
				startActivity(intent);
				
			}
		});
		
		lastRowView = new LinearLayout(this);

		LayoutInflater vi = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		vi.inflate(R.layout.comment_list_load, lastRowView, true);
		
		//新浪按了载入更多是整个列表更新，腾讯只更新部分列表
		switch (platformType) {
    	
			case Platform.SINA_PLATFORM:
				
				 lastRowView.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
			
							progressDialog = ProgressDialog.show(CommentListActivity.this, null, "载入更多评论");
						
							new Thread(){

								public void run() {
														
									loadMore();

								}	
								
							}.start();
						
					}
				 });
				 
				 break;
				 
			case Platform.TENCENT_PLATFORM:
				
				 lastStateText = (TextView) lastRowView.findViewById(R.id.comment_lastStateText);
				 
				 lastLoading = (ProgressBar) lastRowView.findViewById(R.id.comment_lastLoading);
				 
				 lastRowView.setOnClickListener(new OnClickListener() {

						public void onClick(View v) {
				
								lastStateText.setText(R.string.loading);
								
								lastLoading.setVisibility(View.VISIBLE);
								
								new Thread(){

									public void run() {
											
										loadMore();

									}	
									
								}.start();
							
						}
				});
				 
			     break;
			default:break;
		
		}
		
		this.getListView().addFooterView(lastRowView);
	}
	
	/**
	 * 初始化数据
	 */
	private void initData(){
			
		progressDialog = ProgressDialog.show(this, null, "载入中");
		
		new Thread(){

			public void run() {
				
				try {
					
					initCommentList();
					
					commentAdapter  = new CommentAdapter(CommentListActivity.this, R.layout.comment_item, commentList);
					
					CommentListActivity.this.runOnUiThread(new Runnable() {
						
						public void run() {
							
							CommentListActivity.this.setListAdapter(commentAdapter);
							
							progressDialog.dismiss();
							
						}
					});
					
				} catch (WeiboException e) {
					
					e.printStackTrace();
					
					CommentListActivity.this.runOnUiThread(new Runnable() {
						
						public void run() {

							progressDialog.dismiss();
							
							Toast.makeText(CommentListActivity.this, "载入失败", Toast.LENGTH_SHORT).show();
							
						}
					});
			
				} catch (JSONException e) {
					
					e.printStackTrace();
					
					CommentListActivity.this.runOnUiThread(new Runnable() {
						
						public void run() {

							progressDialog.dismiss();
							
							Toast.makeText(CommentListActivity.this, "载入失败", Toast.LENGTH_SHORT).show();
							
						}
					});	
				}		
			}

    	}.start();
	}
	
	/**
	 * 初始化载入列表
	 * @throws WeiboException 
	 * @throws JSONException 
	 */
	private void initCommentList() throws WeiboException, JSONException{
    	
		commentList = new ArrayList<Comment>();
    	
    	switch (platformType) {
    	
			case Platform.SINA_PLATFORM:
				 		
				 Weibo weibo = OAuthConstant.getInstance().getWeibo();
				
				 //初始化时默认载入20条
				 String resultString = weibo.getCommentsJSONString(mblog.getId(),20);
					 
				 commentList = transferSinaCommentJSONStringToList(resultString);
	 
				 break;
				 
			case Platform.TENCENT_PLATFORM:
				 
				 SharedPreferences preference = getSharedPreferences("tencent_qauth",Context.MODE_PRIVATE);
				
				 QWeiboSyncApi api = new QWeiboSyncApi();
				 
				 String result = api.getCommentList(OAuth.AppKey, OAuth.AppSecret,preference.getString("AccessToken", null),preference.getString("AccessTokenSecret", null), ResultType.ResultType_Json, mblog.getId(), "0", "0");
				 
				 commentList = transferTencentCommentJSONStringToList(result);
				 
				 break;	
			default:
				
				 break;
		}
    	
	}

	private void loadMore(){
		
		try {
		
			switch (platformType) {
			
				case Platform.SINA_PLATFORM:
					 		
					 Weibo weibo = OAuthConstant.getInstance().getWeibo();
					 
					 int nowCount = this.commentList.size();
	
					 int count;
					 
					 if(nowCount < 20){
						 
						 count = 40;
						 
					 }else{
						
						 count = (nowCount/20 + 1)*20;
					 }
					 
					 String resultString = weibo.getCommentsJSONString(mblog.getId(),count);
						 
					 commentList = transferSinaCommentJSONStringToList(resultString);
						
					 CommentListActivity.this.runOnUiThread(new Runnable() {
						
						public void run() {
							
							CommentListActivity.this.commentAdapter.update(CommentListActivity.this.commentList);
							
						}
						
					 });
					 
					 progressDialog.dismiss();
					 
					 break;
					 
				case Platform.TENCENT_PLATFORM:
					 		
					 SharedPreferences preference = getSharedPreferences("tencent_qauth",Context.MODE_PRIVATE);
					
					 QWeiboSyncApi api = new QWeiboSyncApi();
					 
					 int nowCount2 = commentAdapter.getCount();
					 
					 String lastId;
					 
					 String pagetime;
					 
					 if(nowCount2 == 0){
						 
						 lastId = "0";
						 
						 pagetime = "0";
					 }else{
					     
						 Comment lastComment = (Comment)commentAdapter.getItem(nowCount2 - 1);
						 
						 lastId = lastComment.getId();
						 
						 pagetime = TimeUtil.formatDateToTencentString(lastComment.getCreate_at());
							 
					 }
					 
					 String result = api.getCommentList(OAuth.AppKey, OAuth.AppSecret,preference.getString("AccessToken", null),preference.getString("AccessTokenSecret", null), ResultType.ResultType_Json, mblog.getId(), lastId,pagetime);
					
					 this.commentList.addAll(transferTencentCommentJSONStringToList(result));
					 
					 CommentListActivity.this.runOnUiThread(new Runnable() {
						
						public void run() {
							
							 commentAdapter.update(commentList);
							 
							 lastStateText.setText(R.string.loadMore);
								
							 lastLoading.setVisibility(View.GONE);
							 
						}
					 });
						
					 break;	
					 
				default:
					
					 break;
			}
						
		} catch (WeiboException e) {

			e.printStackTrace();
			
			CommentListActivity.this.runOnUiThread(new Runnable() {
				
				public void run() {
					
					//新浪会触发这个异常		
					if(platformType == Platform.SINA_PLATFORM)
						progressDialog.dismiss();
					
					if(platformType == Platform.TENCENT_PLATFORM){
							
						lastStateText.setText(R.string.loadMore);
						
						lastLoading.setVisibility(View.GONE);
					
					}
					
				}
			});
			
			Looper.prepare();
			
			Toast.makeText(CommentListActivity.this, "载入失败", Toast.LENGTH_SHORT).show();
		
			Looper.loop();
		} catch (JSONException e) {
			
			e.printStackTrace();
			
			CommentListActivity.this.runOnUiThread(new Runnable() {
				
				public void run() {
					
					//新浪会触发这个异常		
					if(platformType == Platform.SINA_PLATFORM)
						progressDialog.dismiss();
					
					if(platformType == Platform.TENCENT_PLATFORM){
							
						lastStateText.setText(R.string.loadMore);
						
						lastLoading.setVisibility(View.GONE);
					
					}
					
				}
			});
		
			Looper.prepare();
			
			Toast.makeText(CommentListActivity.this, "载入失败", Toast.LENGTH_SHORT).show();
			
			Looper.loop();
		}

	}

	private List<Comment> transferSinaCommentJSONStringToList(String jsonString) throws JSONException{
		 
		 List<Comment> list = new ArrayList<Comment>();
		
		 JSONArray jsonArray = new JSONArray(jsonString);
		
		 for(int i = 0;i<jsonArray.length();i++){
				 
			JSONObject jsonObject = jsonArray.getJSONObject(i);
				 
			Comment comment = new Comment(jsonObject.getString("id"), jsonObject.getJSONObject("user").getString("id"),jsonObject.getJSONObject("user").getString("screen_name"),jsonObject.getString("text"), TimeUtil.formatSinaStringToDate(jsonObject.getString("created_at")));
				 
			list.add(comment);
				 
		 }
		 
		return list;
	}
	
	private List<Comment> transferTencentCommentJSONStringToList(String jsonString) throws JSONException{
		
		List<Comment> list = new ArrayList<Comment>();
		
		if(!new JSONObject(jsonString).isNull("data")){
			JSONArray commentArray = new JSONObject(jsonString).getJSONObject("data").getJSONArray("info");
			 
			for(int i=0;i<commentArray.length();i++){
				 
				 JSONObject jsonObject = (JSONObject) commentArray.get(i);
				 
				 //腾讯拿不到uid，用name作为唯一标识
				 Comment comment = new Comment(jsonObject.getString("id"), jsonObject.getString("name"),jsonObject.getString("nick"),jsonObject.getString("text"), TimeUtil.formatTencentStringToDate(jsonObject.getString("timestamp")));
				 
				 list.add(comment);
				 
			}
		} 
		return list;
	}
}
